package org.jinyan.admin.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jinyan.admin.controller.UserController;
import org.jinyan.admin.model.MyUser;
import org.jinyan.utils.Md5;
import org.jinyan.utils.RemoteServiceUtil;

public class LoginServlet extends HttpServlet {

	private Logger logger = Logger.getLogger(RemoteServiceUtil.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");

		String userUuid = req.getParameter("account");
		String userPwd = req.getParameter("password");
		System.out.println(userUuid + "用户登录");
		logger.info(userUuid + "用户登录");
		UserController userService = new UserController();
		MyUser user = null;
		try {
			System.out.println("用户登录验证");
			user = userService.login(userUuid, userPwd);
		} catch (SQLException e) {
			System.out.println("用户登录出现异常" + e.getLocalizedMessage());
			logger.error("用户登录", e);
			e.printStackTrace();
		}
		if (user != null) {
			// 转发模式 将 index.jsp网页中得到数据转发给success，jsp中
			System.out.println(userUuid + "用户登录成功");
			logger.info(userUuid + "用户登录成功");
			HttpSession session = req.getSession(true);
			session.setAttribute("Useruuid",
					Md5.md5s(userUuid + new Date().toString()));
			user.setPassword(null);
			session.setAttribute("myuser", user);
			//req.setAttribute("User", user);
			req.getRequestDispatcher("index.jsp").forward(req, resp);
		} else {
			req.setAttribute("fail", "登录失败");
			req.getRequestDispatcher("login.jsp").forward(req, resp);
			// resp.sendRedirect("error.jsp");
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}
